<template>
  <div class="clients-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>客户端管理 (总数: {{ filteredClients.length }})</span>
          <el-button type="primary" @click="refreshClients">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </template>

      <div class="filters">
        <el-input
            v-model="searchQuery"
            placeholder="搜索客户端ID、IP、流名或应用名"
            prefix-icon="Search"
            clearable
            style="width: 300px; margin-right: 12px"
            @keyup.enter="handleSearch"
        />
        <el-select
            v-model="clientType"
            placeholder="选择客户端类型"
            clearable
            style="width: 150px; margin-right: 12px"
            @change="handleSearch"
        >
          <el-option label="推流端" value="publisher" />
          <el-option label="拉流端" value="player" />
        </el-select>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetFilters">重置</el-button>
      </div>

      <el-table
          v-loading="loading"
          :data="paginatedClients"
          style="width: 100%; margin-top: 16px"
          border
          :row-style="{ cursor: 'pointer' }"
          @row-click="viewClientDetail" >
        <el-table-column type="index" label="#" width="60" />
        <el-table-column prop="id" label="客户端ID" min-width="180" show-overflow-tooltip>
          <template #default="scope">
            <el-tag size="small">{{ scope.row.id }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="ip" label="客户端IP" min-width="120" show-overflow-tooltip />

        <el-table-column prop="type" label="类型" width="100" fixed="left">
          <template #default="scope">
            <el-tag
                :type="scope.row.publish ? 'success' : 'primary'"
                effect="dark"
                size="small"
            >
              {{ scope.row.publish ? '推流端' : '拉流端' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="app" label="应用名" min-width="100" show-overflow-tooltip />
        <el-table-column prop="stream" label="流名称" min-width="180" show-overflow-tooltip>
          <template #default="scope">
            <el-tag v-if="scope.row.stream" size="small" type="info">{{ scope.row.stream }}</el-tag>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column prop="vhost" label="虚拟主机" min-width="120" show-overflow-tooltip />

        <el-table-column prop="alive" label="存活时间" min-width="120">
          <template #default="scope">
            {{ formatDuration(scope.row.alive) }}
          </template>
        </el-table-column>
        <el-table-column prop="send_bytes" label="发送流量" min-width="120">
          <template #default="scope">
            {{ formatBytes(scope.row.send_bytes) }}
          </template>
        </el-table-column>
        <el-table-column prop="recv_bytes" label="接收流量" min-width="120">
          <template #default="scope">
            {{ formatBytes(scope.row.recv_bytes) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button
                type="danger"
                size="small"
                @click.stop="confirmDisconnect(scope.row)"
            >
              断开
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination" v-if="!loading && filteredClients.length > 0">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="filteredClients.length"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <el-dialog
        v-model="detailVisible"
        title="客户端详情"
        width="600px"
        :before-close="closeDetailDialog"
    >
      <div v-if="selectedClient">
        <el-descriptions :column="1" border size="small">
          <el-descriptions-item label="客户端ID">{{ selectedClient.id }}</el-descriptions-item>
          <el-descriptions-item label="IP地址">{{ selectedClient.ip }}</el-descriptions-item>
          <el-descriptions-item label="类型">
            <el-tag :type="selectedClient.publish ? 'success' : 'primary'">
              {{ selectedClient.publish ? '推流端' : '拉流端' }} ({{ selectedClient.type }})
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="存活时间">{{ formatDuration(selectedClient.alive) }}</el-descriptions-item>
          <el-descriptions-item label="应用名 (App)">{{ selectedClient.app }}</el-descriptions-item>
          <el-descriptions-item label="流名称">{{ selectedClient.stream || '--' }}</el-descriptions-item>
          <el-descriptions-item label="发送字节">{{ formatBytes(selectedClient.send_bytes) }}</el-descriptions-item>
          <el-descriptions-item label="接收字节">{{ formatBytes(selectedClient.recv_bytes) }}</el-descriptions-item>
          <el-descriptions-item label="发送速率 (30s)">{{ selectedClient.kbps.send_30s }} kbps</el-descriptions-item>
          <el-descriptions-item label="接收速率 (30s)">{{ selectedClient.kbps.recv_30s }} kbps</el-descriptions-item>

          <el-descriptions-item label="-- 访问地址 --" label-class-name="label-group"></el-descriptions-item>
          <el-descriptions-item label="传输控制URL (tcUrl)">
            <el-text tag="p" style="word-break: break-all;">{{ selectedClient.tcUrl || '--' }}</el-text>
          </el-descriptions-item>
          <el-descriptions-item label="资源路径 (url)">
            <el-text tag="p" style="word-break: break-all;">{{ selectedClient.url || '--' }}</el-text>
          </el-descriptions-item>
          <el-descriptions-item label="页面地址 (pageUrl)">{{ selectedClient.pageUrl || '--' }}</el-descriptions-item>
          <el-descriptions-item label="SWF地址 (swfUrl)">{{ selectedClient.swfUrl || '--' }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDetailDialog">关闭</el-button>
          <el-button type="danger" @click="confirmDisconnect(selectedClient)">断开连接</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
        v-model="confirmVisible"
        title="确认断开连接"
        width="400px"
    >
      <div v-if="clientToDisconnect">
        <p>确定要断开客户端 <strong>{{ clientToDisconnect.id }}</strong> 的连接吗？</p>
        <p style="color: #606266; margin-top: 10px;">
          IP: {{ clientToDisconnect.ip }}<br>
          类型: {{ clientToDisconnect.publish ? '推流端' : '拉流端' }}<br>
          流: {{ clientToDisconnect.stream || 'N/A' }}
        </p>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="confirmVisible = false">取消</el-button>
          <el-button type="danger" @click="disconnectClient">确认断开</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>


<script>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { Refresh, Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'Clients',
  components: {
    Refresh,
    Search
  },
  setup() {
    const loading = ref(false)
    const searchQuery = ref('')
    const clientType = ref('')
    const clients = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const detailVisible = ref(false)
    const confirmVisible = ref(false)
    const selectedClient = ref(null)
    const clientToDisconnect = ref(null)

    /**
     * 从客户端 URL 或 tcUrl 解析应用名 (app name)
     */
    const extractAppName = (client) => {
      const url = client.url || client.tcUrl
      if (!url) return '未知'

      let path;
      try {
        if (url.startsWith('http') || url.startsWith('rtmp')) {
          const urlObj = new URL(url.startsWith('rtmp') ? url.replace('rtmp', 'http') : url);
          path = urlObj.pathname.split('/').filter(p => p);
        } else {
          path = url.split('/').filter(p => p);
        }
      } catch (e) {
        path = url.split('/').filter(p => p);
      }

      return path.length > 0 ? path[0] : '未知'
    }

    // 获取客户端列表 (使用直接的API请求方式)
    const getClients = async () => {
      loading.value = true
      try {
        // 使用直接的fetch API调用
        const response = await fetch('/api/v1/clients/')
        const data = await response.json()

        // 检查响应是否成功 (HTTP 状态码 200-299)
        if (response.ok) {
          if (data.code === 0) {
            clients.value = (data.clients || []).map(client => ({
              ...client,
              // 预处理，添加 app 字段
              app: extractAppName(client)
            }))
          } else {
            ElMessage.error(data.message || '获取客户端列表失败')
          }
        } else {
          // HTTP 状态码错误
          ElMessage.error(`获取客户端失败: HTTP错误 ${response.status} ${response.statusText}`)
        }
      } catch (err) {
        console.error('获取客户端失败:', err)
        ElMessage.error('网络错误或服务器连接失败')
      } finally {
        loading.value = false
      }
    }

    // 刷新客户端列表
    const refreshClients = () => {
      currentPage.value = 1
      getClients()
    }

    /**
     * **FIX: 添加查看客户端详情的函数**
     * 点击表格行时触发，显示客户端详情对话框。
     */
    const viewClientDetail = (client) => {
      selectedClient.value = client
      detailVisible.value = true
      // 可以在此处添加逻辑来请求更详细的客户端数据（如果 API 支持）
      // getClientDetail(client.id)
    }

    // 确认断开连接
    const confirmDisconnect = (client) => {
      if(detailVisible.value) {
        detailVisible.value = false;
      }
      clientToDisconnect.value = client
      confirmVisible.value = true
    }

    // 断开客户端连接 (使用直接的API请求方式)
    const disconnectClient = async () => {
      if (!clientToDisconnect.value) return

      try {
        // 使用直接的fetch API调用
        const response = await fetch(`/api/v1/clients/${clientToDisconnect.value.id}`, {
          method: 'DELETE'
        })
        
        // 检查响应是否成功 (HTTP 状态码 200-299)
        if (response.ok) {
          const data = await response.json()
          if (data.code === 0) {
            ElMessage.success(`客户端 ${clientToDisconnect.value.id} 已断开连接`)

            confirmVisible.value = false
            detailVisible.value = false

            // 从列表中移除断开的客户端
            clients.value = clients.value.filter(c => c.id !== clientToDisconnect.value.id)
            clientToDisconnect.value = null
            refreshClients()
          } else {
            // API 返回的错误信息
            ElMessage.error(data.message || '断开连接失败: API返回错误代码')
          }
        } else {
          // HTTP 状态码错误
          ElMessage.error(`断开连接失败: HTTP错误 ${response.status} ${response.statusText}`)
        }

      } catch (err) {
        console.error('断开连接失败:', err)
        ElMessage.error('网络错误或服务器连接失败')
      }
    }

    // 关闭详情对话框
    const closeDetailDialog = () => {
      detailVisible.value = false
      selectedClient.value = null
    }

    // 搜索
    const handleSearch = () => {
      currentPage.value = 1
    }

    // 重置筛选条件
    const resetFilters = () => {
      searchQuery.value = ''
      clientType.value = ''
      currentPage.value = 1
    }

    // 页码和每页数量变化处理
    const handleSizeChange = (size) => {
      pageSize.value = size
      currentPage.value = 1
    }

    const handleCurrentChange = (current) => {
      currentPage.value = current
    }

    // 格式化时长 (HH小时MM分钟SS秒)
    const formatDuration = (seconds) => {
      if (typeof seconds !== 'number' || seconds < 0) return '--'
      const totalSeconds = Math.round(seconds)
      const hours = Math.floor(totalSeconds / 3600)
      const minutes = Math.floor((totalSeconds % 3600) / 60)
      const secs = totalSeconds % 60

      const h = hours > 0 ? `${hours}小时` : ''
      const m = minutes > 0 ? `${minutes}分钟` : ''
      const s = `${secs}秒`

      return `${h}${m}${s}`.trim() || '0秒'
    }

    // 格式化字节数 (B, KB, MB, GB, TB)
    const formatBytes = (bytes) => {
      if (bytes === 0 || typeof bytes !== 'number' || bytes < 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    }

    // 过滤后的客户端列表
    const filteredClients = computed(() => {
      let result = clients.value

      // 按搜索词过滤 (ID, IP, Stream, App)
      if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase()
        result = result.filter(client =>
            client.id.toLowerCase().includes(query) ||
            client.ip.toLowerCase().includes(query) ||
            (client.stream && client.stream.toLowerCase().includes(query)) ||
            (client.app && client.app.toLowerCase().includes(query))
        )
      }

      // 按客户端类型过滤 (根据 publish 字段)
      if (clientType.value === 'publisher') {
        result = result.filter(client => client.publish === true)
      } else if (clientType.value === 'player') {
        result = result.filter(client => client.publish === false)
      }

      return result
    })

    // 分页后的客户端列表
    const paginatedClients = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      return filteredClients.value.slice(start, end)
    })

    let refreshTimer = null

    onMounted(() => {
      getClients()

      // 定时刷新
      refreshTimer = setInterval(() => {
        if (!loading.value) {
          getClients()
        }
      }, 10000) // 10秒刷新一次
    })

    onUnmounted(() => {
      if (refreshTimer) {
        clearInterval(refreshTimer)
      }
    })

    return {
      loading,
      searchQuery,
      clientType,
      clients,
      currentPage,
      pageSize,
      detailVisible,
      confirmVisible,
      selectedClient,
      clientToDisconnect,
      filteredClients,
      paginatedClients,
      refreshClients,
      viewClientDetail, // **FIX: 导出 viewClientDetail 函数**
      confirmDisconnect,
      disconnectClient,
      closeDetailDialog,
      handleSearch,
      resetFilters,
      handleSizeChange,
      handleCurrentChange,
      formatDuration,
      formatBytes
    }
  }
}
</script>

<style scoped>
.clients-container {
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filters {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  flex-wrap: wrap;
  gap: 12px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  text-align: right;
}

/* 详情对话框样式 */
:deep(.el-descriptions__label) {
  width: 130px !important; /* 统一标签宽度 */
}
:deep(.label-group) {
  font-weight: bold;
  background: #f0f9eb !important; /* 强调地址信息的标签 */
}
</style>